package j41;

/**
 * @author chengshuai
 * @date 2021/4/15 13:13
 */

public class ProduceConsumeSync {

    private int number = 0;
    public synchronized void increment() {
        //1、判断
        while (number != 0) {
            //等待，不能生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //2、干活
        number++;
        System.out.println(Thread.currentThread().getName() + "\t" + number);
        //3、通知唤醒
        this.notifyAll();
    }

    public synchronized void decrement() {
            //1、判断
            while (number == 0) {
                //等待，不能消费
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //2、干活
            number--;
            System.out.println(Thread.currentThread().getName() + "\t" + number);
            //3、通知唤醒
            this.notifyAll();
    }

    public static void main(String[] args) {
        ProduceConsumeSync produceConsume = new ProduceConsumeSync();
        new Thread(() -> {
            for (int i = 0; i < 2; i++) {
                produceConsume.increment();
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 2; i++) {
                produceConsume.decrement();
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 2; i++) {
                produceConsume.increment();
            }
        }, "CC").start();

        new Thread(() -> {
            for (int i = 0; i < 2; i++) {
                produceConsume.decrement();
            }
        }, "DD").start();
    }
}
